<?php if (!defined("BASEPATH")) exit("No direct script access allowed");

class Main extends MY_Controller {

	function __construct() {
		parent::__construct();
	}

	function _remap($param) {
		if(method_exists($this, $param)) {
			$func_get_args = func_get_args();
			$this->$param((count($func_get_args) == 2 and isset($func_get_args[1][0]))?($func_get_args[1][0]):(NULL));
		} else {
			// elso paraméter continent vagy article

			$presenter = (($this->uri->segment(1) == "preview")?(" in ('I', 'N') "):(" = 'I' "));
			$args = func_get_args();
			//Common::pr($args);
			
			// institute hierarchikus linkek miatt feluliras
			if(($this->uri->segment(1) == "institutes" or ($this->uri->segment(1) == "preview" and $this->uri->segment(2) == "institutes")) and isset($args[1]) and count($args[1] > 3)) {
				for($i = 3; $i <= count($args[1])-1; $i++) {
					$args[1][2] .= "/".$args[1][$i];
				}
				for($j = 3; $j < $i; $j++) {
					unset($args[1][$j]);
				}
				//Common::pr($args); exit;
				// check - institute
				$this->load->model("institute");
				$getInstitute = $this->institute->getInstitute($where = "ins_url_name = '".$this->db->escape_str($args[1][2])."' and ins_presenter ".$presenter);
				if(!count($getInstitute)) {
					// ha nem akkor majorrel probalkozunk
					$arr12 = explode("/", $args[1][2]);
					$args[1][3] = $arr12[count($arr12)-1];
					unset($arr12[count($arr12)-1]);
					$args[1][2] = implode("/", $arr12);
				}
				unset($getInstitute);
			}
			//Common::pr($args); exit;

			// Programtype felülírás, egyelore csak study-abroad van
			//$param = "study-abroad";

			$getSzotar = array(
				"PROGTYPE" => array(
					"study-abroad" => array(
						"szoLname" => "Study Abroad",
						"szoUrlName" => "study-abroad",
					)
				)
			);
			
			$programType = FALSE;
			if($args[0] <> "study-abroad") {

				$this->load->model("article_model");
				$getArticle = $this->article_model->getArticle($where = "art_url_name = '".$this->db->escape_str($param)."' ".(($this->uri->segment(1) != "preview")?(" and art_name is not null "):("")));

				// semester, high-school, winter-term
				$this->load->model("szotar");
				$getSzotar = $this->szotar->getSzotar(array("PROGTYPE", "PROGTYPE_2"), $urlName = TRUE);
				$getSzotar["PROGTYPE"] += $getSzotar["PROGTYPE_2"];
				unset($getSzotar["PROGTYPE_2"]);
				foreach($getSzotar["PROGTYPE"] as $szoSname => $szoData) {
					if($szoData["szoUrlName"] == $args[0]) {
						$param = $szoSname;
						$programType = TRUE;
					}
				}
				
				if(!count($getArticle) and !$programType) {
					$tmpargs1 = array($args[0]);
					foreach($args[1] as $val) {
						$tmpargs1[] = $val;
					}
					$args[1] = $tmpargs1;
				}
				
			} else {
				$programType = TRUE;
				$args[0] = "study-abroad";
			}

			if(count($args[1]) > 0 and in_array($args[1][0], $this->config->item("study-abroad-programs"))) {
				$this->load->model("szotar");
				$getSzotar = $this->szotar->getSzotar(array("PROGTYPE", "PROGTYPE_2"), $urlName = TRUE);
				// programtype
				$getSzotar["PROGTYPE"] += $getSzotar["PROGTYPE_2"];
				foreach($getSzotar["PROGTYPE"] as $szoSname => $szoData) {
					if($szoData["szoUrlName"] == $args[1][0]) {
						$param = $szoSname;
						$programType = TRUE;
					}
				}
				$tmpargs1 = array();
				foreach($args[1] as $ii => $val) {
					if($ii) {
						$tmpargs1[] = $val;
					}
				}
				$args[1] = $tmpargs1;
			}

			// continent/country url ...
			if(!$programType) {

				$this->load->model("szotar");
				$getSzotar = $this->szotar->getSzotar(array("PROGTYPE", "PROGTYPE_2"), $urlName = TRUE);
				// programtype
				$getSzotar["PROGTYPE"] += $getSzotar["PROGTYPE_2"];
				foreach($getSzotar["PROGTYPE"] as $szoSname => $szoData) {
					if($szoData["szoUrlName"] == $param) {
						$param = $szoSname;
						$programType = TRUE;
					}
				}

				$tmpargs1 = array();
				foreach($args[1] as $ii => $val) {
					if($ii or (!$programType)) {
						$tmpargs1[] = $val;
					}
				}
				$args[1] = $tmpargs1;
			}

			//Common::pr($args); exit;
			//var_dump($programType); echo $param."<br/>"; Common::pr($args); Common::pr($getSzotar); exit;
			
			switch(count($args[1])) {

				case 0: {
					if($programType) {
						$this->index($getArticle = FALSE, $programType = $param, $getSzotar);
					} else {
						// article
						//$this->load->model("article_model");
						//$getArticle = $this->article_model->getArticle($where = "art_url_name = '".$this->db->escape_str($param)."'");
						if(count($getArticle)) {
							$this->index($getArticle);
						} else {
							redirect("errors/error_404");
						}
					}
				} break;

				case 1: {
					$this->load->model("continent");
					$getContinent = $this->continent->getContinent($where = "con_url_name = '".$this->db->escape_str($args[1][0])."'");
					if(count($getContinent)) {
						// continent
						$this->_continent($getContinent, $programType = (($programType)?($param):("")), $getSzotar);
					} else {
						redirect("errors/error_404");
					}
				} break;

				case 2: {
					$this->load->model("country");
					$getCountry = $this->country->getCountry($where = "cou_url_name = '".$this->db->escape_str($args[1][1])."' and cou_presenter ".$presenter);
					if(count($getCountry)) {
						// country
						$this->_country($getCountry, $programType = (($programType)?($param):("")), $getSzotar);
					} else {
						redirect("errors/error_404");
					}
				} break;

				case 3: {
					$this->load->model("city");
					$getCity = $this->city->getCity($where = "city_url_name = '".$this->db->escape_str($args[1][2])."' and city_presenter ".$presenter);
					if(count($getCity)) {
						// city
						$this->_city($getCity, $programType = (($programType)?($param):("")), $getSzotar);
					} else {
						redirect("errors/error_404");
					}
				} break;

				case 4: {
					$this->load->model("institute");
					$getInstitute = $this->institute->getInstitute($where = "ins_url_name = '".$this->db->escape_str($args[1][3])."' and ins_presenter ".$presenter);
					if(count($getInstitute)) {
						// institute
						$this->_institute($getInstitute);
					} else {
						redirect("errors/error_404");
					}
				} break;

				case 5: {
					$this->load->model("major");
					$getMajor = $this->major->getMajor($where = "maj_url_name = '".$this->db->escape_str($args[1][4])."' and ins_url_name = '".$this->db->escape_str($args[1][3])."' and maj_presenter ".$presenter);
					if(count($getMajor)) {
						// major
						$this->_major($getMajor);
					} else {
						redirect("errors/error_404");
					}
				} break;

				case 6: {
					switch($args[1][4]) {
						case "scholarships": {
							$this->load->model("scholarship");
							$getScholarship = $this->scholarship->getScholarship($where = "sch_url_name = '".$this->db->escape_str($args[1][5])."' and sch_presenter ".$presenter);
							if(count($getScholarship)) {
								// scholarship
								$this->_scholarship($getScholarship);
							} else {
								redirect("errors/error_404");
							}
						} break;
						case "accomodations": {
							$this->load->model("accomodation");
							$getAccomodation = $this->accomodation->getAccomodation($where = "acc_url_name = '".$this->db->escape_str($args[1][5])."' and acc_presenter ".$presenter);
							if(count($getAccomodation)) {
								// accomodation
								$this->_accomodation($getAccomodation);
							} else {
								redirect("errors/error_404");
							}
						} break;
					}
				} break;
				
				default: {
					redirect("errors/error_404");
				} break;

			}

		}
	}

	function get_unread_messages() {
		$this->db->cache_off();
		$this->load->model("usr2ent");
		$this->load->model("message");
		$sajatUniqueIds = $this->message->where("(mes_sender_usr_id = ".intval($this->session->userdata("usrId"))." or mes_reader_usr_id = ".intval($this->session->userdata("usrId")).")")->groupBy("mes_unique_id")->select("mes_unique_id")->getAll();
		$arrUniqueIds = array();
		foreach($sajatUniqueIds as $std) {
			$arrUniqueIds[] = $std->mes_unique_id;
		}
		$cnt = 0;
		if(count($sajatUniqueIds)) {
			$cnt = $this->message->getUnreadMessagesCnt($where = "mes_unique_id in (".implode(",", $arrUniqueIds).") and mes_sender_usr_id != ".$this->session->userdata("usrId"));
		}

		$this->page["content"] = $cnt;
		$this->load->view("template/empty", $this->page);
	}


	function index($getArticle = FALSE, $programType = FALSE, $params = array()) {

		$params += $this->_sidebar();
		$params["content"] = "";
		$params["getArticleKiemelt"] = $this->article_model->getArticle($where = "art_highlight = 'I' and art_name is not null", $start = NULL, $limit = NULL, $fields = NULL, $query = NULL, $order = "artOrder");

		if($getArticle) {
			$params["getArticle"] = $getArticle;
			$params["content"] = $this->load->view("page/article", $params, TRUE);
			$params["breadcrumbs"] = array(
				site_url() => $this->lang->line("HOME"),
				$getArticle[0]["artName"],
			);
			$params["share"] = TRUE;
			$params["title"] = $getArticle[0]["artName"];
		} else {

			$args = func_get_args();

			if($programType) {
				$params["breadcrumbs"] = array(
					site_url() => $this->lang->line("HOME"),
				);
				if(in_array($args[2]["PROGTYPE"][$programType]["szoUrlName"], $this->config->item("study-abroad-programs"))) {
					$params["breadcrumbs"][site_url()."study-abroad"] = $this->lang->line("STUDY_ABROAD");
				}
				$params["breadcrumbs"][] = $args[2]["PROGTYPE"][$programType]["szoLname"];
				$params["title"] = $args[2]["PROGTYPE"][$programType]["szoLname"]." ".((in_array($args[2]["PROGTYPE"][$programType]["szoUrlName"], $this->config->item("study-abroad-programs")))?($this->lang->line("STUDY_ABROAD")." "):(""))." ".$this->lang->line("PROGRAMS");
			} else {
				$params["breadcrumbs"] = array(
					$this->lang->line("HOME"),
				);
			}

			$params["getArticleList"] = $this->article_model->getArticle($where = "art_highlight = 'N' and art_position = 'C' and art_name is not null", $start = NULL, $limit = 10, $fields = NULL, $query = NULL, $order = "artCreatetime", $dir = "DESC");
			$params["content"] = $this->load->view("page/article_list", $params, TRUE);

			// featured countries
			if($programType) {
				$this->load->model("country");
				$getCountry = $this->country->getCountry($where = "cou_presenter ".(($this->uri->segment(1) == "preview")?(" in ('I', 'N') "):(" = 'I' "))." ".(($programType <> "study-abroad")?(" and (maj_prog_type = '".$this->db->escape_str($programType)."' or maj_prog_type2 = '".$this->db->escape_str($programType)."')"):("")), $start = NULL, $limit = NULL, $fields = NULL, $query = NULL, $order = "rand()", $dir = "DESC");
				if(count($getCountry)) {
					$sumPriority = 0;
					foreach($getCountry as $d) {
						$sumPriority += $d["couPriority"];
					}
					$selectedCountries = array();
					$arrCountryCity = array();
					for($i = 0; $i < 3; $i++) {
						$rand = rand(0, $sumPriority);
						$aktSumPriority = 0;
						foreach($getCountry as $ii => $d) {
							if(!in_array($d["couId"], $selectedCountries)) {
								$aktSumPriority += $d["couPriority"];
								if($aktSumPriority >= $rand) {
									$selectedCountries[] = $d["couId"];
									$arrCountryCity[$d["couId"]]["couImageNameThumb"] = $d["couImageNameThumb"];
									$arrCountryCity[$d["couId"]]["couImageAlt"] = $d["couImageAlt"];
									$arrCountryCity[$d["couId"]]["couUrlName"] = $d["conName"];
									$arrCountryCity[$d["couId"]]["conUrlName"] = $d["conUrlName"];
									$arrCountryCity[$d["couId"]]["couName"] = $d["couName"];
									$sumPriority -= $d["couPriority"];
									break;
								}
							}
						}
					}
					if(count($selectedCountries)) {
						$this->load->model("city");
						$getCity = $this->city->getCity($where = "city_presenter ".(($this->uri->segment(1) == "preview")?(" in ('I', 'N') "):(" = 'I' "))." ".(($programType <> "study-abroad")?(" and (maj_prog_type = '".$this->db->escape_str($programType)."' or maj_prog_type2 = '".$this->db->escape_str($programType)."') "):(""))." and city_cou_id in (".implode(",", $selectedCountries).")", $start = NULL, $limit = NULL, $fields = NULL, $query = NULL, $order = "rand()", $dir = "DESC");
						$sumPriority = 0;
						foreach($getCity as $d) {
							$arrCountryCity[$d["cityCouId"]]["couUrlName"] = $d["couUrlName"];
							$arrCountryCity[$d["cityCouId"]]["conUrlName"] = $d["conUrlName"];
							$arrCountryCity[$d["cityCouId"]]["couName"] = $d["couName"];
							$arrCountryCity[$d["cityCouId"]]["cities"][$d["cityId"]] = $d;
							$sumPriority += $d["cityPriority"];
						}
						foreach($arrCountryCity as $couId => $couData) {
							if(isset($couData["cities"])) {
								$selectedCities = array();
								$arrCities = array();
								for($i = 0; $i < 3; $i++) {
									$rand = rand(0, $sumPriority);
									$aktSumPriority = 0;
									foreach($couData["cities"] as $cityId => $d) {
										if(!in_array($cityId, $selectedCities)) {
											$aktSumPriority += $d["cityPriority"];
											if($aktSumPriority >= $rand) {
												$selectedCities[] = $cityId;
												$arrCities[] = $d;
												break;
											}
										}
									}
									$arrCountryCity[$couId]["cities"] = $arrCities;
								}
							}
						}
						$params["content"] .= $this->load->view("page/featured_cities", array("arrCountryCity" => $arrCountryCity), TRUE);
					}
				}
			}


			// Program Spotlight
			/*
			$this->load->model("city");
			$getCity = $this->city->getCity($where = "e2c_id is not null".(($programType)?(" and (maj_prog_type = '".$this->db->escape_str($programType)."' or maj_prog_type2 = '".$this->db->escape_str($programType)."')"):("")), $start = NULL, $limit = NULL, $fields = NULL, $query = NULL, $order = "rand()", $dir = "DESC");
			if(count($getCity)) {
				$sumPriority = 0;
				foreach($getCity as $d) {
					$sumPriority += $d["cityPriority"];
				}
				$selectedCities = array();
				$arrCity = array();
				for($i = 0; $i < 3; $i++) {
					$rand = rand(0, $sumPriority);
					$aktSumPriority = 0;
					foreach($getCity as $ii => $d) {
						if(!in_array($d["cityId"], $selectedCities)) {
							$aktSumPriority += $d["cityPriority"];
							if($aktSumPriority >= $rand) {
								$selectedCities[] = $d["cityId"];
								$arrCity[$d["cityId"]]["cityName"] = $d["cityName"];
								$arrCity[$d["cityId"]]["cityImageNameThumb"] = $d["cityImageNameThumb"];
								$arrCity[$d["cityId"]]["cityImageAlt"] = $d["cityImageAlt"];
								$arrCity[$d["cityId"]]["cityUrlName"] = $d["cityUrlName"];
								$arrCity[$d["cityId"]]["couUrlName"] = $d["couUrlName"];
								$arrCity[$d["cityId"]]["conUrlName"] = $d["conUrlName"];
								$sumPriority -= $d["cityPriority"];
								break;
							}
						}
					}
				}
				if(count($selectedCities)) {
					//$this->load->model("major");
					//$getMajor = $this->major->getMajor($where = "maj_", $start = NULL, $limit = NULL, $fields = NULL, $query = NULL, $order = "majName", $dir = "ASC"
					$params["content"] .= $this->load->view("page/program_spotlight", array("arrCity" => $arrCity), TRUE);
				}
			}
			*/

			$this->load->model("institute");
			$getInstitute = $this->institute->getInstitute($where = "ins_presenter ".(($this->uri->segment(1) == "preview")?(" in ('I', 'N') "):(" = 'I' "))." and maj_del = 0 ".(($programType <> "study-abroad")?(" and (maj_prog_type = '".$this->db->escape_str($programType)."' or maj_prog_type2 = '".$this->db->escape_str($programType)."')"):("")), $start = NULL, $limit = NULL, $fields = NULL, $query = NULL, $order = "rand()", $dir = "DESC");
			if(count($getInstitute)) {

				$this->load->model("country");
				$params["getCityInstitute"] = $this->country->getCityInstitute($where = "city_presenter ".(($this->uri->segment(1) == "preview")?(" in ('I', 'N') "):(" = 'I' "))." " . (($programType and $programType <> "study-abroad")?(" and maj_presenter ".(($this->uri->segment(1) == "preview")?(" in ('I', 'N') "):(" = 'I' "))." and (maj_prog_type = '".$this->db->escape_str($programType)."' or maj_prog_type2 = '".$this->db->escape_str($programType)."')"):("")));
				$params["google_map_big"] = $this->load->view("page/google_map", $params, TRUE);

				$sumPriority = 0;
				foreach($getInstitute as $d) {
					$sumPriority += $d["insPriority"];
				}
				$selectedInstitutes = array();
				$arrInstitute = array();
				for($i = 0; $i < 3; $i++) {
					$rand = rand(0, $sumPriority);
					$aktSumPriority = 0;
					foreach($getInstitute as $ii => $d) {
						if(!in_array($d["insId"], $selectedInstitutes)) {
							$aktSumPriority += $d["insPriority"];
							if($aktSumPriority >= $rand) {
								$selectedInstitutes[] = $d["insId"];
								$arrInstitute[$d["insId"]]["insName"] = $d["insName"];
								$arrInstitute[$d["insId"]]["insImageNameThumb"] = $d["insImageNameThumb"];
								$arrInstitute[$d["insId"]]["insImageAlt"] = $d["insImageAlt"];
								$arrInstitute[$d["insId"]]["insUrlName"] = $d["insUrlName"];
								$sumPriority -= $d["insPriority"];
								break;
							}
						}
					}
				}
				if(count($selectedInstitutes)) {
					$this->load->model("major");
					$getMajor = $this->major->getMajor($where = "maj_presenter ".(($this->uri->segment(1) == "preview")?(" in ('I', 'N') "):(" = 'I' "))." ".(($programType <> "study-abroad")?(" and (maj_prog_type = '".$this->db->escape_str($programType)."' or maj_prog_type2 = '".$this->db->escape_str($programType)."')"):(""))." and maj_ins_id in (".implode(",", $selectedInstitutes).")", $start = NULL, $limit = NULL, $fields = NULL, $query = NULL, $order = "rand()", $dir = "ASC");
					foreach($getMajor as $majData) {
						if(!isset($arrInstitute[$majData["majInsId"]]["majName"])) {
							$arrInstitute[$majData["majInsId"]]["majName"] = $majData["majName"];
							$arrInstitute[$majData["majInsId"]]["majUrlName"] = $majData["majUrlName"];
							$arrInstitute[$majData["majInsId"]]["cityName"] = $majData["cityName"];
						}
					}
					$params["content"] .= $this->load->view("page/program_spotlight", array("arrInstitute" => $arrInstitute), TRUE);
				}
			}

		}

		$this->load->view("template/page", $params);

	}

	function _continent($getContinent, $programType = "") {

		$args = func_get_args();

		$params = $this->_sidebar();

		$params["ENTITY"] = "CON";

		$params["getArticleKiemelt"] = $this->article_model->getArticle($where = "art_highlight = 'I' and art_name is not null", $start = NULL, $limit = NULL, $fields = NULL, $query = NULL, $order = "artOrder");

		$params["breadcrumbs"][site_url()] = $this->lang->line("HOME");
		if($programType) {
			if(in_array($args[2]["PROGTYPE"][$programType]["szoUrlName"], $this->config->item("study-abroad-programs"))) {
				$params["breadcrumbs"][site_url()."study-abroad"] = $this->lang->line("STUDY_ABROAD");
			}
			$params["breadcrumbs"][site_url().((in_array($args[2]["PROGTYPE"][$programType]["szoUrlName"], $this->config->item("study-abroad-programs")))?("study-abroad/"):("")).$args[2]["PROGTYPE"][$programType]["szoUrlName"]] = $args[2]["PROGTYPE"][$programType]["szoLname"];
		}
		$params["breadcrumbs"][] = $getContinent[0]["conName"];

		$params["title"] = $args[2]["PROGTYPE"][$programType]["szoLname"]." ".((in_array($args[2]["PROGTYPE"][$programType]["szoUrlName"], $this->config->item("study-abroad-programs")))?($this->lang->line("STUDY_ABROAD")." "):(""))." ".$this->lang->line("PROGRAMS");
		$params["title"] .= " in ".$getContinent[0]["conName"];
		$params["pagetitle"] = $getContinent[0]["conName"];

		$this->load->model("ent2cat");
		$params["content"] = $this->load->view("page/show_category", $params + array("getEnt2cat" => $this->ent2cat->getEnt2cat($where = "e2c_entity = 'CON' and e2c_ent_id = '".$this->db->escape_str($getContinent[0]["conId"])."' ".(($this->uri->segment(1) == "preview")?(""):(" and coalesce(e2c_int, e2c_text) is not null ")))), TRUE);

		//$this->load->model("institute");
		//$params["getInstitute"] = $this->institute->getInstitute($where = "e2c_id is not null and ins_id is not null and con_id = '".$this->db->escape_str($getContinent[0]["conId"])."'", $start = NULL, $limit = NULL, $fields = NULL, $query = NULL, $order = "rand()", $dir = "DESC");
		$this->load->model("country");
		$params["getCityInstitute"] = $this->country->getCityInstitute($where = "ins_presenter ".(($this->uri->segment(1) == "preview")?(" in ('I', 'N') "):(" = 'I' "))." and con_id = '".$this->db->escape_str($getContinent[0]["conId"])."'".(($programType and $programType <> "study-abroad")?(" and (maj_prog_type = '".$this->db->escape_str($programType)."' or maj_prog_type2 = '".$this->db->escape_str($programType)."')"):("")));
		$params["google_map_big"] = $this->load->view("page/google_map", $params, TRUE);

		$this->load->view("template/page", $params);

	}

	function _country($getCountry, $programType = "") {
		$args = func_get_args();

		$params["getArticleByEntId"] = $this->article_model->getArticleByEntId("e2a_cou_id = ".$getCountry[0]["couId"]);
		$params = $this->_sidebar($params);

		$params["getCountry"] = $getCountry;
		$params["ENTITY"] = "COU";

		$params["breadcrumbs"][site_url()] = $this->lang->line("HOME");
		if($programType) {
			if(in_array($args[2]["PROGTYPE"][$programType]["szoUrlName"], $this->config->item("study-abroad-programs"))) {
				$params["breadcrumbs"][site_url()."study-abroad"] = $this->lang->line("STUDY_ABROAD");
			}
			$params["breadcrumbs"][site_url().((in_array($args[2]["PROGTYPE"][$programType]["szoUrlName"], $this->config->item("study-abroad-programs")))?("study-abroad/"):("")).$args[2]["PROGTYPE"][$programType]["szoUrlName"]] = $args[2]["PROGTYPE"][$programType]["szoLname"];
		}
		$params["breadcrumbs"][site_url().(($programType)?(((in_array($args[2]["PROGTYPE"][$programType]["szoUrlName"], $this->config->item("study-abroad-programs")))?("study-abroad/"):("")).$args[2]["PROGTYPE"][$programType]["szoUrlName"]."/"):("")).$getCountry[0]["conUrlName"]] = $getCountry[0]["conName"];
		$params["breadcrumbs"][] = $getCountry[0]["couName"];

		$params["title"] = $params["pagetitle"] = (($programType and in_array($args[2]["PROGTYPE"][$programType]["szoUrlName"], $this->config->item("study-abroad-programs")))?($args[2]["PROGTYPE"][$programType]["szoLname"]." "):("")).$this->lang->line("STUDY_ABROAD")." ".$this->lang->line("PROGRAMS")." in ".$getCountry[0]["couName"];

		$params["entName"] = $getCountry[0]["couName"];

		$this->load->model("ent2cat");
		$params["getEnt2cat"] = $this->ent2cat->getEnt2cat($where = "e2c_entity = 'COU' and e2c_ent_id = '".$this->db->escape_str($getCountry[0]["couId"])."' ".(($this->uri->segment(1) == "preview")?(""):(" and coalesce(e2c_int, e2c_text) is not null ")));
		$params["getCityInstitute"] = $this->country->getCityInstitute($where = "ins_presenter ".(($this->uri->segment(1) == "preview")?(" in ('I', 'N') "):(" = 'I' "))." and cou_id = '".$this->db->escape_str($getCountry[0]["couId"])."'".(($programType and $programType <> "study-abroad")?(" and (maj_prog_type = '".$this->db->escape_str($programType)."' or maj_prog_type2 = '".$this->db->escape_str($programType)."')"):("")));
		$this->load->model("ent2image");
		$params["getEnt2image"] = $this->ent2image->getEnt2image($where = "e2i_cou_id = '".$this->db->escape_str($getCountry[0]["couId"])."'");
		$params["content"] = $this->load->view("page/show_category", $params, TRUE);

		$params["google_map"] = $this->load->view("page/google_map", $params, TRUE);

		$this->load->model("major");
		//$params["getProgType"] = $this->major->getProgType($where = "cou_id = '".$this->db->escape_str($getCountry[0]["couId"])."'");
		$params["getProgType"] = $this->major->getProgType();
		$params["selectedProgType"] = ((count($params["getProgType"]) and isset($params["getProgType"][$programType]))?($programType):(""));

		if($params["selectedProgType"]) {
			$params["getAvailablePrograms"] = $this->major->getAvailablePrograms($where = "maj_presenter ".(($this->uri->segment(1) == "preview")?(" in ('I', 'N') "):(" = 'I' "))." and cou_id = '".$this->db->escape_str($getCountry[0]["couId"])."' and (maj_prog_type = '".$this->db->escape_str($params["selectedProgType"])."' or maj_prog_type2 = '".$this->db->escape_str($params["selectedProgType"])."')");
		} else {
			$params["getAvailablePrograms"] = array();
			foreach($params["getProgType"] as $type => $typeData) {
				if(count($params["getAvailablePrograms"])) {
					continue;
				}
				$params["selectedProgType"] = $type;
				$params["getAvailablePrograms"] = $this->major->getAvailablePrograms($where = "maj_presenter ".(($this->uri->segment(1) == "preview")?(" in ('I', 'N') "):(" = 'I' "))." and cou_id = '".$this->db->escape_str($getCountry[0]["couId"])."' and (maj_prog_type = '".$this->db->escape_str($type)."' or maj_prog_type = '".$this->db->escape_str($type)."')");
			}
		}

		$params["content2"] = $this->load->view("page/show_major", $params, TRUE);

		$this->load->view("template/page", $params);

	}

	function _city($getCity, $programType = "") {
		//Common::pr($getCity);

		$args = func_get_args();

		$params["getArticleByEntId"] = $this->article_model->getArticleByEntId("e2a_city_id = ".$getCity[0]["cityId"]);
		$params = $this->_sidebar($params);

		$params["getCity"] = $getCity;
		$params["ENTITY"] = "CITY";

		$params["breadcrumbs"][site_url()] = $this->lang->line("HOME");
		if($programType) {
			if(in_array($args[2]["PROGTYPE"][$programType]["szoUrlName"], $this->config->item("study-abroad-programs"))) {
				$params["breadcrumbs"][site_url()."study-abroad"] = $this->lang->line("STUDY_ABROAD");
			}
			$params["breadcrumbs"][site_url().((in_array($args[2]["PROGTYPE"][$programType]["szoUrlName"], $this->config->item("study-abroad-programs")))?("study-abroad/"):("")).$args[2]["PROGTYPE"][$programType]["szoUrlName"]] = $args[2]["PROGTYPE"][$programType]["szoLname"];
		}
		$params["breadcrumbs"][site_url().(($programType)?(((in_array($args[2]["PROGTYPE"][$programType]["szoUrlName"], $this->config->item("study-abroad-programs")))?("study-abroad/"):("")).$args[2]["PROGTYPE"][$programType]["szoUrlName"]."/"):("")).$getCity[0]["conUrlName"]] = $getCity[0]["conName"];
		$params["breadcrumbs"][site_url().(($programType)?(((in_array($args[2]["PROGTYPE"][$programType]["szoUrlName"], $this->config->item("study-abroad-programs")))?("study-abroad/"):("")).$args[2]["PROGTYPE"][$programType]["szoUrlName"]."/"):("")).$getCity[0]["conUrlName"]."/".$getCity[0]["couUrlName"]] = $getCity[0]["couName"];
		$params["breadcrumbs"][] = $getCity[0]["cityName"];

		$params["title"] = $getCity[0]["cityName"]." - ".$getCity[0]["couName"];
		$params["title"] = $params["pagetitle"] = $this->lang->line("STUDY_ABROAD")." ".$this->lang->line("PROGRAMS")." in ".$getCity[0]["cityName"]." - ".$getCity[0]["couName"];
		$params["pagetitle"] =  $this->lang->line("STUDY_ABROAD")." ".$this->lang->line("PROGRAMS")." in ".$getCity[0]["cityName"];

		$params["entName"] = $getCity[0]["cityName"];

		$this->load->model("institute");
		$params["getInstitute"] = $this->institute->getInstitute($where = "ins_city_id = '".$this->db->escape_str($getCity[0]["cityId"])."' and ins_presenter ".(($this->uri->segment(1) == "preview")?(" in ('I', 'N') "):(" = 'I' "))."", $start = NULL, $limit = NULL, $fields = NULL, $query = NULL, $order = "insName", $dir = "ASC", $getAddresses = TRUE);

		$this->load->model("ent2cat");
		$params["getEnt2cat"] = $this->ent2cat->getEnt2cat($where = "e2c_entity = 'CITY' and e2c_ent_id = '".$this->db->escape_str($getCity[0]["cityId"])."' ".(($this->uri->segment(1) == "preview")?(""):(" and coalesce(e2c_int, e2c_text) is not null ")));
		$this->load->model("ent2image");
		$params["getEnt2image"] = $this->ent2image->getEnt2image($where = "e2i_city_id = '".$this->db->escape_str($getCity[0]["cityId"])."'");
		$params["content"] = $this->load->view("page/show_category", $params, TRUE);

		$params["google_map"] = $this->load->view("page/google_map", $params, TRUE);

		$this->load->model("major");
		//$params["getProgType"] = $this->major->getProgType($where = "city_id = '".$this->db->escape_str($getCity[0]["cityId"])."'");
		$params["getProgType"] = $this->major->getProgType();
		$params["selectedProgType"] = ((count($params["getProgType"]) and isset($params["getProgType"][$programType]))?($programType):(""));

		if($params["selectedProgType"]) {
			$params["getAvailablePrograms"] = $this->major->getAvailablePrograms($where = "maj_presenter ".(($this->uri->segment(1) == "preview")?(" in ('I', 'N') "):(" = 'I' "))." and city_id = '".$this->db->escape_str($getCity[0]["cityId"])."' and (maj_prog_type = '".$this->db->escape_str($params["selectedProgType"])."' or maj_prog_type2 = '".$this->db->escape_str($params["selectedProgType"])."')");
		} else {
			$params["getAvailablePrograms"] = array();
			foreach($params["getProgType"] as $type => $typeData) {
				if(count($params["getAvailablePrograms"])) {
					continue;
				}
				$params["selectedProgType"] = $type;
				$params["getAvailablePrograms"] = $this->major->getAvailablePrograms($where = "maj_presenter ".(($this->uri->segment(1) == "preview")?(" in ('I', 'N') "):(" = 'I' "))." and city_id = '".$this->db->escape_str($getCity[0]["cityId"])."' and (maj_prog_type = '".$this->db->escape_str($type)."' or maj_prog_type2 = '".$this->db->escape_str($type)."')");
			}
		}

		$params["content2"] = $this->load->view("page/show_major", $params, TRUE);

		$this->load->view("template/page", $params);

	}

	function _institute($getInstitute) {
		//Common::pr($getInstitute);
		$this->load->model("institute_address");

		$params["getArticleByEntId"] = $this->article_model->getArticleByEntId("e2a_ins_id = ".$getInstitute[0]["insId"]);
		$params = $this->_sidebar($params);

		$params["getInstitute"] = $getInstitute;
		$params["getInstituteAddresses"] = $this->institute_address->addressMapper($this->institute_address->where("add_ins_id", $getInstitute[0]["insId"])->getAll());
		$params["ENTITY"] = "INS";
		$params["share"] = TRUE;

		$params["breadcrumbs"] = array(
			site_url() => $this->lang->line("HOME"),
			site_url().$getInstitute[0]["conUrlName"] => $getInstitute[0]["conName"],
			site_url().$getInstitute[0]["conUrlName"]."/".$getInstitute[0]["couUrlName"] => $getInstitute[0]["couName"],
			site_url().$getInstitute[0]["conUrlName"]."/".$getInstitute[0]["couUrlName"]."/".$getInstitute[0]["cityUrlName"] => $getInstitute[0]["cityName"],
		);
		if($getInstitute[0]["insInsId"]) {
			$getParents = $this->institute->getParents($getInstitute[0]["insInsId"], "ins_presenter ".(($this->uri->segment(1) == "preview")?(" in ('I', 'N') "):(" = 'I' "))."");
			if(count($getParents)) {
				foreach($getParents as $insId => $insData) {
					$params["breadcrumbs"][site_url()."institutes/".$insData["insUrlName"]] = $insData["insName"];
				}
			}
		}
		$params["breadcrumbs"][] = $getInstitute[0]["insName"];

		$params["getChildren"] = $this->institute->getChildren($getInstitute[0]["insId"], "ins_presenter ".(($this->uri->segment(1) == "preview")?(" in ('I', 'N') "):(" = 'I' "))."");

		$params["title"] = $getInstitute[0]["insName"]." - ".$getInstitute[0]["cityName"]." - ".$getInstitute[0]["couName"];
		$params["pagetitle"] = $getInstitute[0]["insName"];

		$params["entName"] = $getInstitute[0]["insName"];
		
		$this->load->model("accomodation");
		$params["getAccomodation"] = $this->accomodation->getAccomodation($where = "a2im_ins_id = '".$this->db->escape_str($getInstitute[0]["insId"])."' and acc_presenter ".(($this->uri->segment(1) == "preview")?(" in ('I', 'N') "):(" = 'I' "))."");
		
		$this->load->model("ent2cat");
		$params["getEnt2cat"] = $this->ent2cat->getEnt2cat($where = "e2c_entity in ('INS', 'FAC') and e2c_ent_id = '".$this->db->escape_str($getInstitute[0]["insId"])."' ".(($this->uri->segment(1) == "preview")?(""):(" and coalesce(e2c_int, e2c_text) is not null ")));
		$params["contactForm"] = $this->load->view("page/contact_form", array("insId" => $getInstitute[0]["insId"]), TRUE);

		$this->load->model("ent2image");
		$params["getEnt2image"] = $this->ent2image->getEnt2image($where = "e2i_ins_id = '".$this->db->escape_str($getInstitute[0]["insId"])."'");
		if(!count($params["getEnt2image"])) {
			$this->load->model("institute");
			$getParents = $this->institute->getParents($getInstitute[0]["insId"]);
			if(count($getParents) > 1) {
				$getParents = array_reverse($getParents, TRUE);
				$ii = 0;
				foreach($getParents as $parInsId => $parData) {
					if($ii) {
						$params["getEnt2image"] = $this->ent2image->getEnt2image($where = "e2i_ins_id = '".$this->db->escape_str($parInsId)."'");
						if(count($params["getEnt2image"])) break;
					}
					$ii++;
				}
			}
		}
		$params["content"] = $this->load->view("page/show_category", $params, TRUE);

		$params["google_map"] = $this->load->view("page/google_map", $params, TRUE);

		$this->load->model("major");
		$params["getProgType"] = array("ALL" => array("szoLname" => $this->lang->line("ALL"), "szoUrlName" => "all")) + $this->major->getProgType($where = "ins_id = '".$this->db->escape_str($getInstitute[0]["insId"])."'");

		//Common::pr($params["getProgType"]); exit;
		$params["selectedProgType"] = ((count($params["getProgType"]))?(key($params["getProgType"])):(""));

		if($params["selectedProgType"]) {
			$params["getAvailablePrograms"] = $this->major->getAvailablePrograms($where = "maj_presenter ".(($this->uri->segment(1) == "preview")?(" in ('I', 'N') "):(" = 'I' "))." and kar.ins_id = '".$this->db->escape_str($getInstitute[0]["insId"])."'".(($params["selectedProgType"] != "ALL")?(" and (maj_prog_type = '".$this->db->escape_str($params["selectedProgType"])."' or maj_prog_type2 = '".$this->db->escape_str($params["selectedProgType"])."')"):("")));
		}

		$params["content2"] = $this->load->view("page/show_major", $params, TRUE);

		$this->load->view("template/page", $params);

	}

	function _accomodation($getAccomodation) {
		//Common::pr($getAccomodation);

		$params = $this->_sidebar();

		$params["getAccomodation"] = $getAccomodation;
		$params["ENTITY"] = "ACC";
		$params["share"] = TRUE;

		$params["breadcrumbs"] = array(
			site_url() => $this->lang->line("HOME"),
			//site_url().$getAccomodation[0]["conUrlName"] => $getAccomodation[0]["conName"],
			//site_url().$getAccomodation[0]["conUrlName"]."/".$getAccomodation[0]["couUrlName"] => $getAccomodation[0]["couName"],
			//site_url().$getAccomodation[0]["conUrlName"]."/".$getAccomodation[0]["couUrlName"]."/".$getAccomodation[0]["cityUrlName"] => $getAccomodation[0]["cityName"],
			//site_url()."institutes/".$getAccomodation[0]["insUrlName"] => $getAccomodation[0]["insName"],
		);
		$params["breadcrumbs"][] = $getAccomodation[0]["accName"]." - ".$getAccomodation[0]["insNameList"];

		$params["title"] = $getAccomodation[0]["accName"]." - ".$getAccomodation[0]["insNameList"];
		$params["pagetitle"] = $getAccomodation[0]["accName"];

		$params["entName"] = $getAccomodation[0]["accName"];

		$this->load->model("ent2cat");
		$params["getEnt2cat"] = $this->ent2cat->getEnt2cat($where = "e2c_entity = 'ACC' and e2c_ent_id = '".$this->db->escape_str($getAccomodation[0]["accId"])."' ".(($this->uri->segment(1) == "preview")?(""):(" and coalesce(e2c_int, e2c_text) is not null ")));

		$this->load->model("ent2image");
		$params["getEnt2image"] = $this->ent2image->getEnt2image($where = "e2i_acc_id = '".$this->db->escape_str($getAccomodation[0]["accId"])."'");
		$params["content"] = $this->load->view("page/show_category", $params, TRUE);

		$params["google_map"] = $this->load->view("page/google_map", $params, TRUE);

		$this->load->view("template/page", $params);

	}
	
	function _major($getMajor) {
		//Common::pr($getMajor);

		$params["getMajor"] = $getMajor;
		$params["ENTITY"] = "MAJ";
		$params["share"] = TRUE;

		$params["breadcrumbs"] = array(
			site_url() => $this->lang->line("HOME"),
			site_url().$getMajor[0]["conUrlName"] => $getMajor[0]["conName"],
			site_url().$getMajor[0]["conUrlName"]."/".$getMajor[0]["couUrlName"] => $getMajor[0]["couName"],
			site_url().$getMajor[0]["conUrlName"]."/".$getMajor[0]["couUrlName"]."/".$getMajor[0]["cityUrlName"] => $getMajor[0]["cityName"],
			//site_url().$getMajor[0]["conUrlName"]."/".$getMajor[0]["couUrlName"]."/".$getMajor[0]["cityUrlName"]."/".$getMajor[0]["insUrlName"] => $getMajor[0]["insName"],
		);

		$this->load->model("institute");
		$getParents = $this->institute->getParents($getMajor[0]["majInsId"], "ins_presenter ".(($this->uri->segment(1) == "preview")?(" in ('I', 'N') "):(" = 'I' "))."");
		if(count($getParents)) {
			foreach($getParents as $insId => $insData) {
				$params["breadcrumbs"][site_url()."institutes/".$insData["insUrlName"]] = $insData["insName"];
			}
		} else {
			redirect("", "refresh");
			exit;
		}
		$params["breadcrumbs"][] = $getMajor[0]["majName"];
		//Common::pr($getParents);
		//Common::pr($params["breadcrumbs"]);

		$params["title"] = $getMajor[0]["majName"]." - ".$getMajor[0]["insName"];
		$params["pagetitle"] = $getMajor[0]["majName"]." - ".$getMajor[0]["insName"];

		$params["entName"] = $getMajor[0]["majName"];

		$this->load->model("accomodation");
		$params["getAccomodation"] = $this->accomodation->getAccomodation($where = "a2im_maj_id = '".$this->db->escape_str($getMajor[0]["majId"])."' and acc_presenter ".(($this->uri->segment(1) == "preview")?(" in ('I', 'N') "):(" = 'I' "))."");
		
		$this->load->model("ent2cat");
		$params["getEnt2cat"] = $this->ent2cat->getEnt2cat($where = "e2c_entity = 'MAJ' and e2c_ent_id = '".$this->db->escape_str($getMajor[0]["majId"])."' ".(($this->uri->segment(1) == "preview")?(""):(" and coalesce(e2c_int, e2c_text) is not null ")));

		if(isset($params["getEnt2cat"][$this->config->item("categoryMAJFeeCurrencyId")]) and $params["getEnt2cat"][$this->config->item("categoryMAJFeeCurrencyId")]["e2cInt"]) {
			$this->load->model("currency");
			$currency = $this->currency->getById($params["getEnt2cat"][$this->config->item("categoryMAJFeeCurrencyId")]["e2cInt"]);
			//common::pr($params["currencyList"]);
			$params["getEnt2cat"][$this->config->item("categoryMAJFeeCurrencyId")]["e2cInt"] = $currency->curr_text;
		}
		
		$this->load->model("ent2image");
		$params["getEnt2image"] = $this->ent2image->getEnt2image($where = "e2i_maj_id = '".$this->db->escape_str($getMajor[0]["majId"])."'");
		if(!count($params["getEnt2image"])) {
			$params["getEnt2image"] = $this->ent2image->getEnt2image($where = "e2i_ins_id = '".$this->db->escape_str($getMajor[0]["majInsId"])."'");
			if(empty($params["getEnt2image"])) {
				$this->load->model("institute");
				$getParents = $this->institute->getParents($getMajor[0]["majInsId"]);
				if(count($getParents) > 1) {
					$getParents = array_reverse($getParents, TRUE);
					$ii = 0;
					foreach($getParents as $parInsId => $parData) {
						if($ii) {
							$params["getEnt2image"] = $this->ent2image->getEnt2image($where = "e2i_ins_id = '".$this->db->escape_str($parInsId)."'");
							if(count($params["getEnt2image"])) break;
						}
						$ii++;
					}
				}
			}
		}
	
		$params["content"] = $this->load->view("page/show_category", $params, TRUE);

		$this->load->model("institute");
		$params["getInstitute"] = $this->institute->getInstitute($where = "ins_presenter ".(($this->uri->segment(1) == "preview")?(" in ('I', 'N') "):(" = 'I' "))." and ins_url_name = '".$this->db->escape_str($getMajor[0]["insUrlName"])."'");
		$params["google_map"] = $this->load->view("page/google_map", $params, TRUE);

		$this->load->model("ent2cat");
		$params["insName"] = $getMajor[0]["insName"];
		$params["getInsEnt2cat"] = $this->ent2cat->getEnt2cat($where = "e2c_entity in ('INS', 'FAC') and e2c_ent_id = '".$this->db->escape_str($getMajor[0]["majInsId"])."' and cat_type != 'T' ".(($this->uri->segment(1) == "preview")?(""):(" and coalesce(e2c_int, e2c_text) is not null ")));

		$params["contactForm"] = $this->load->view("page/contact_form", array("insId" => $getMajor[0]["majInsId"]), TRUE);
		$params["getArticleByEntId"] = $this->article_model->getArticleByEntId("e2a_maj_id = ".$getMajor[0]["majId"]);
		$params["sidebar"] = $this->load->view("page/sidebar", $params, TRUE);

		$this->load->view("template/page", $params);

	}

	function _scholarship($getScholarship) {
		//Common::pr($getScholarship);

		$params["getScholarship"] = $getScholarship;
		$params["ENTITY"] = "SCH";
		$params["share"] = TRUE;

		$params["breadcrumbs"] = array(
			site_url() => $this->lang->line("HOME"),
			//site_url().$getScholarship[0]["conUrlName"] => $getScholarship[0]["conName"],
			//site_url().$getScholarship[0]["conUrlName"]."/".$getScholarship[0]["couUrlName"] => $getScholarship[0]["couName"],
			//site_url().$getScholarship[0]["conUrlName"]."/".$getScholarship[0]["couUrlName"]."/".$getScholarship[0]["cityUrlName"] => $getScholarship[0]["cityName"],
			//site_url().$getScholarship[0]["conUrlName"]."/".$getScholarship[0]["couUrlName"]."/".$getScholarship[0]["cityUrlName"]."/".$getScholarship[0]["insUrlName"] => $getScholarship[0]["insName"],
			site_url()."scholarships" => $this->lang->line("SCHOLARSHIPS"),
			$getScholarship[0]["schName"]
		);
		$params["title"] = $params["pagetitle"] = $getScholarship[0]["schName"];;

		$params["entName"] = $getScholarship[0]["schName"];
		
		$this->load->model("ent2image");
		$params["getEnt2image"] = $this->ent2image->getEnt2image($where = "e2i_sch_id = '".$this->db->escape_str($getScholarship[0]["schId"])."'");
		
		$this->load->model("ent2cat");
		$params["getEnt2cat"] = $this->ent2cat->getEnt2cat($where = "e2c_entity = 'SCH' and e2c_ent_id = '".$this->db->escape_str($getScholarship[0]["schId"])."' ".(($this->uri->segment(1) == "preview")?(""):(" and coalesce(e2c_int, e2c_text) is not null ")));
		$params["content"] = $this->load->view("page/show_category", $params, TRUE);

		$this->load->model("institute");
		$params["getInstitute"] = $this->institute->getInstitute($where = "ins_presenter ".(($this->uri->segment(1) == "preview")?(" in ('I', 'N') "):(" = 'I' "))." and ins_id in (".implode(",", array_keys($getScholarship[0]["INS"])).")");
		$params["google_map"] = $this->load->view("page/google_map", $params, TRUE);
		
		$this->load->model("ent2cat");
		$sidebar = "";
		$params["more_ins"] = $getScholarship[0]["INS"];
		$elso = TRUE;
		foreach($getScholarship[0]["INS"] as $insId => $insData) {
			$params["insName"] = $insData["insName"];
			$params["getInsEnt2cat"] = $this->ent2cat->getEnt2cat($where = "e2c_entity in ('INS', 'FAC') and e2c_ent_id = '".$this->db->escape_str($insId)."' and cat_type != 'T'  ".(($this->uri->segment(1) == "preview")?(""):(" and coalesce(e2c_int, e2c_text) is not null ")));
			if(!$elso) {
				$params["more_ins"] = array();
				$params["style"] = "display: none;";
			}
			$params["contactForm"] = $this->load->view("page/contact_form", array("insId" => $insId), TRUE);
			$sidebar .= $this->load->view("page/sidebar", $params, TRUE);
			$elso = FALSE;
		}
		$params["sidebar"] = $sidebar;

		$this->load->view("template/page", $params);

	}
	
	function tabmenu_refresh() {
		/*
		$current_url = preg_split("/\//", $this->input->post("current_url"), NULL, PREG_SPLIT_NO_EMPTY);
		$arr = array(
			2 => "cou",
			3 => "city",
			4 => "ins",
		);
		*/

		//if(isset($arr[count($current_url)])) {
			if($this->input->post("url_name") and $this->input->post("entity") and in_array($this->input->post("entity"), array("COU", "CITY", "INS"))) {

			//$url_name = $current_url[count($current_url) - 1];

			$url_name = $this->input->post("url_name");
			$params["url_name"] = $url_name;
			$entity = strtolower($this->input->post("entity"));

			$this->load->model("major");
			$params["getProgType"] = (($entity == "ins")?(array("ALL" => array("szoLname" => $this->lang->line("ALL"), "szoUrlName" => "all"))):(array())) + $this->major->getProgType($where = $entity."_url_name= '".$this->db->escape_str($url_name)."'");
			$params["selectedProgType"] = ((count($params["getProgType"]) and isset($params["getProgType"][$this->input->post("program_type")]))?($this->input->post("program_type")):(""));

			if($params["selectedProgType"]) {

				$params["entName"] = $this->input->post("entName");
				$params["ENTITY"] = $this->input->post("entity");

				// pager
				$pageSize = $this->config->item("availableProgramPageSize");
				$page = Common::coalesce(array($this->input->post("page"), 1));

				$params["getAvailablePrograms"] = $this->major->getAvailablePrograms($where = "maj_presenter ".(($this->uri->segment(1) == "preview")?(" in ('I', 'N') "):(" = 'I' "))." and ".(($this->input->post("entity") == "INS")?("kar."):("")).$entity."_url_name = '".$this->db->escape_str($url_name)."'".(($params["selectedProgType"] != "ALL")?(" and maj_prog_type = '".$this->db->escape_str($params["selectedProgType"])."'"):("")), ($page-1)*$pageSize, $pageSize);

				$content = $this->load->view("page/show_major", $params, TRUE);
				echo $content;
				echo	"<script type=\"text/javascript\">accordion();</script>";

			}

		}

	}

	function login_form() {
		if($this->session->userdata("usrId")) redirect("", "refresh");
		header("Content-Type: text/javascript");

		$login = $this->load->view("page/login", array(), TRUE);
		echo	"\$('#modal').html('".$this->db->escape_str($login)."');";
		echo	"\$('#modal').width(800);";
		echo	"\$('#modal').modal({overlayClose : true});";
		echo	"\$('#usrEmail').focus();";
	}

	function forgot_password_form() {
		if($this->session->userdata("usrId")) redirect("", "refresh");
		header("Content-Type: text/javascript");

		$forgot_password = $this->load->view("page/forgot_password", array(), TRUE);
		echo	"\$('#modal').html('".$this->db->escape_str($forgot_password)."');";
		echo	"\$('#modal').width(800);";
		echo	"\$('#modal').modal({});";
		echo	"\$('#usrEmail').focus();";
	}

	function openid($provider = NULL, $admin = FALSE) {
		include_once APPPATH . "libraries/Google/autoload.php";
		$client_id = $this->config->item("GOOGLE_CLIENT_ID");
		$client_secret = $this->config->item("GOOGLE_CLIENT_SECRET");
		$redirect_uri = site_url("openid/google");
		$simple_api_key = $this->config->item("GOOGLE_API_KEY");

		$client = new Google_Client();
		$client->setApplicationName($this->config->item("siteName"));
		$client->setClientId($client_id);
		$client->setClientSecret($client_secret);
		$client->setRedirectUri($redirect_uri);
		$client->setDeveloperKey($simple_api_key);
		$client->addScope(array(
			Google_Service_Oauth2::USERINFO_EMAIL,
			Google_Service_Oauth2::USERINFO_PROFILE,
		));

		// Send Client Request
		$objOAuthService = new Google_Service_Oauth2($client);

		// Add Access Token to Session
		if (isset($_GET['code'])) {
			$client->authenticate($_GET['code']);
			$this->session->set_userdata("access_token", $client->getAccessToken());
			header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
		}

		// Set Access Token to make Request
		if ($this->session->userdata("access_token")) {
			$client->setAccessToken($this->session->userdata("access_token"));
		}

		// Get User Data from Google and store them in $data
		if ($client->getAccessToken()) {
			$userData = $objOAuthService->userinfo->get();
			//common::pr($userData); exit;
			if($userData->email) {
				$this->load->model("user");
				$getUser = $this->user->getUser($where = "usr_email = '".$this->db->escape_str($userData->email)."'");
				if(!$getUser) {
					$insUpd["usr_email"] = $getAttributes['contact/email'];
					$insUpd["usr_registered"] = Common::now();
					$insUpd["usr_newsletter"] = "N";
					$insUpd["usr_logged"] = 0;
					$insUpd["usr_provider"] = "google";
					$insUpd["usr_provider_data"] = json_encode($getAttributes);
					$usrId = $this->user->insert($insUpd);
					$insUpd["grp_name"] = "";
				} else {
					$getUser = current($getUser);
					$insUpd["usr_email"] = $getUser["usrEmail"];
					$insUpd["usr_newsletter"] = $getUser["usrNewsletter"];
					$insUpd["usr_logged"] = $getUser["usrLogged"];
					$insUpd["grp_name"] = $getUser["grpName"];
					$insUpd["usr_provider"] = $getUser["usrProvider"];
					$usrId = $getUser["usrId"];
					$this->user->update($usrId, array("usr_provider_data" => json_encode($userData)));
				}
				
				$this->session->set_userdata("usrId", $usrId);
				$this->session->set_userdata("usrEmail", $insUpd["usr_email"]);
				$this->session->set_userdata("usrNewsletter", $insUpd["usr_newsletter"]);
				$this->session->set_userdata("grpName", $insUpd["grp_name"]);
				$this->session->set_userdata("usrProvider", $insUpd["usr_provider"]);
				
				$this->user->update($usrId, array("usr_logged" => $insUpd["usr_logged"]+1));
				//$subpage["content"] = $this->load->view("page/login", $subpage, TRUE);
				//$this->load->view("template/".(($admin)?("admin_"):(""))."page", $subpage);

				// post controller hook meghivasa redirect elott
				require APPPATH . 'hooks/Daemon_hooks.php'; $hook = new Daemon_hooks(); $hook->call_daemon();

				$this->db->trans_complete();
			} else {
				$this->session->set_flashdata("error", $this->lang->line("GOOGLE_LOGIN_FAILED"));
				$jscallback = "$.ajax({type: 'POST', url: '".site_url("login_form")."', beforeSend: function(xhr) {\$('#body').mask('".$this->db->escape_str($this->lang->line("PLEASE_WAIT,_PROCESSING_IN_PROGRESS"))."');} }).
												always(function() {\$('#body').unmask();});";
				$this->index(FALSE, FALSE, array("jscallback" => $jscallback));
				return;
			}

			//common::pr($userData);  exit;
			//$data['userData'] = $userData;
			$this->session->set_userdata("access_token", $client->getAccessToken());
		} else {
			$authUrl = $client->createAuthUrl();
			$data['authUrl'] = $authUrl;
			//Common::pr($data['authUrl']); exit("itt");
			redirect($data['authUrl']);
		}
		//exit("itt");
		redirect("");

		/*
		$this->load->library("openid", array(site_url()));
		$subpage = array();
		try {
			# Change 'localhost' to your domain name.
			$this->load->library("openid", array(site_url()."openid/google"));
			if(!$this->openid->mode) {
				$this->openid->identity = 'https://www.google.com/accounts/o8/id';
				$this->openid->required = array(
					'namePerson/friendly',
					'contact/email',
					'namePerson',
					'birthDate',
					'person/gender',
					'contact/postalCode/home',
					'contact/country/home',
					'pref/language',
					'pref/timezone',
				);
				//
				//Google					Facebook
				//contact/email			email
				//person/gender			gender
				//namePerson				name
				//namePerson/friendly
				//contact/country/home	location
				//birthDate				birthday  MM/DD/YYYY.
				//pref/timezone			timezone

				//contact/postalCode/home 	Postal code
				//contact/country/home 	locale
				//pref/language 	Language
				//

				header('Location: ' . $this->openid->authUrl());
				exit(0);
			} elseif($this->openid->mode == 'cancel') {
				$subpage["error_message"] = $this->lang->line("USER_HAS_CANCELED_AUTHENTICATION");
			} else {
				//echo 'User ' . ($this->openid->validate() ? $this->openid->identity . ' has ' : 'has not ') . 'logged in.';
				//$subpage["message"] = $this->lang->line("USER_HAS_CANCELED_AUTHENTICATION");
				$getAttributes = $this->openid->getAttributes();
				$this->load->model("user");
				$getUser = $this->user->getUser($where = "usr_email = '".$this->db->escape_str($getAttributes['contact/email'])."'");
				if(!$getUser) {
					$insUpd["usr_email"] = $getAttributes['contact/email'];
					$insUpd["usr_registered"] = Common::now();
					$insUpd["usr_newsletter"] = "N";
					$insUpd["usr_logged"] = 0;
					$insUpd["usr_provider"] = "google";
					$insUpd["usr_provider_data"] = json_encode($getAttributes);
					$usrId = $this->user->insert($insUpd);
					$insUpd["grp_name"] = "";
				} else {
					$getUser = current($getUser);
					$insUpd["usr_email"] = $getUser["usrEmail"];
					$insUpd["usr_newsletter"] = $getUser["usrNewsletter"];
					$insUpd["usr_logged"] = $getUser["usrLogged"];
					$insUpd["grp_name"] = $getUser["grpName"];
					$insUpd["usr_provider"] = $getUser["usrProvider"];
					$usrId = $getUser["usrId"];
					$this->user->update($usrId, array("usr_provider_data" => json_encode($getAttributes)));
				}
				
				$this->session->set_userdata("usrId", $usrId);
				$this->session->set_userdata("usrEmail", $insUpd["usr_email"]);
				$this->session->set_userdata("usrNewsletter", $insUpd["usr_newsletter"]);
				$this->session->set_userdata("grpName", $insUpd["grp_name"]);
				$this->session->set_userdata("usrProvider", $insUpd["usr_provider"]);
				
				$this->user->update($usrId, array("usr_logged" => $insUpd["usr_logged"]+1));
				//$subpage["content"] = $this->load->view("page/login", $subpage, TRUE);
				//$this->load->view("template/".(($admin)?("admin_"):(""))."page", $subpage);

				// post controller hook meghivasa redirect elott
				require APPPATH . 'hooks/Daemon_hooks.php'; $hook = new Daemon_hooks(); $hook->call_daemon();

				$this->db->trans_complete();
				redirect("");

			}
		} catch(ErrorException $e) {
			//echo $e->getMessage();
		}
		*/
	}
	
	function facebook_login() {
		// openId providertől másolva
		$this->load->model("user");
		$getUser = $this->user->getUser($where = "usr_email = '".$this->db->escape_str($this->input->post("email"))."'");
		if(!$getUser) {
			$insUpd["usr_email"] = $this->input->post("email");
			$insUpd["usr_registered"] = Common::now();
			$insUpd["usr_newsletter"] = "N";
			$insUpd["usr_logged"] = 0;
			$insUpd["usr_provider"] = "facebook";
			$insUpd["usr_provider_data"] = json_encode($_POST);
			$usrId = $this->user->insert($insUpd);
			$insUpd["grp_name"] = "";
		} else {
			$getUser = current($getUser);
			$insUpd["usr_email"] = $getUser["usrEmail"];
			$insUpd["usr_newsletter"] = $getUser["usrNewsletter"];
			$insUpd["usr_logged"] = $getUser["usrLogged"];
			$insUpd["grp_name"] = $getUser["grpName"];
			$insUpd["usr_provider"] = $getUser["usrProvider"];
			$usrId = $getUser["usrId"];
			$this->user->update($usrId, array("usr_provider_data" => json_encode($_POST)));
		}
		
		$this->session->set_userdata("usrId", $usrId);
		$this->session->set_userdata("usrEmail", $insUpd["usr_email"]);
		$this->session->set_userdata("usrNewsletter", $insUpd["usr_newsletter"]);
		$this->session->set_userdata("grpName", $insUpd["grp_name"]);
		$this->session->set_userdata("usrProvider", $insUpd["usr_provider"]);
		
		$this->user->update($usrId, array("usr_logged" => $insUpd["usr_logged"]+1));
		
		$this->db->trans_complete();
		// post controller hook meghivasa redirect elott
		require APPPATH . 'hooks/Daemon_hooks.php'; $hook = new Daemon_hooks(); $hook->call_daemon();
		redirect("");
	}

	function registration_form() {

		if($this->session->userdata("usrId")) redirect("", "refresh");
		header("Content-Type: text/javascript");

		$params = array();
		$this->load->model("category");
		$params["getCategory"] = $this->category->getCategory($where = "cat_entity = 'USER'");
		$this->load->model("country");
		$params["getCountry"] = $this->country->getCountry();
		$registration = $this->load->view("registration/registration", $params, TRUE);

		echo	"\$('#modal').html('".$this->db->escape_str($registration)."');";
		echo	"\$('#modal').width(980);";
		echo	"\$('#modal').modal({
			overlayClose : true,
			containerCss: {'height': 'auto !important'}
		});";

	}

	function registration_insert_update() {
		header("Content-Type: application/json");
		$response["error"] = "";

		if(isset($_POST["regType"]) and !$this->input->post("regType")) {
			$response["error"] .= $this->lang->line("TYPE_OF_THE_REGISTRATION_IS_REQUIRED")."<br/>";
		}

		if(isset($_POST["usrEmail"]) and $this->input->post("usrEmail")) {
			$this->load->model("user");
			$getUser = $this->user->getUser($where = "usr_email = '".$this->db->escape_str($this->input->post("usrEmail"))."'");
			if($getUser) {
				$response["error"] .= $this->lang->line("THE_E-MAIL_ADDRESS_IS_RESERVED_PLEASE_SELECT_AN_OTHER")."<br/>";
			}
		}

		if(isset($_POST["usrPassword"])) {
			if(!$this->input->get_post("usrPassword")) {
				$response["error"] .= $this->lang->line("PASSWORD_IS_REQUIRED")."<br/>";
			}
			if($this->input->get_post("usrPassword") and $this->input->get_post("usrPassword") <> $this->input->get_post("usrPasswordRe")) {
				$response["error"] .= $this->lang->line("THE_ENTERED_PASSWORDS_ARE_NOT_THE_SAME")."<br/>";
			}
		}

		if(isset($_POST["usrEmail"])) {
			if(!preg_match("/^[^0-9][A-z0-9_-]+([.][A-z0-9_-]+)*[@][A-z0-9_-]+([.][A-z0-9_-]+)*[.][A-z]{2,4}$/i", $this->input->post("usrEmail"))) {
				$response["error"] .= $this->lang->line("THE_FORMAT_OF_THE_E-MAIL_ADDRESS_IS_INCORRECT")."<br/>";
			}
		}

		$this->load->model("category");
		$getCategory = $this->category->getCategory($where = "cat_entity = 'USER'");
		if(isset($getCategory["USER"])) {
			foreach($getCategory["USER"] as $category) {
				if(isset($_POST["cat_".$category["catId"]])) {
					if($category["catRequired"] == "I" and !$this->input->post("cat_".$category["catId"])) {
						$response["error"] .= $category["catName"].": ".$this->lang->line("THIS_FIELD_IS_REQUIRED")."<br/>";
					}
					if($category["catType"] == "I" and !is_numeric($this->input->post("cat_".$category["catId"]))) {
						$response["error"] .= $category["catName"].": ".$this->lang->line("THE_FIELD_FORMAT_IS_INCORRECT")."<br/>";
					}
				}
			}
		}

		if($this->input->post("finish")) {
			if(!$response["error"]) {
				$insUpd["usr_email"] = $this->input->get_post("usrEmail");
				if($this->input->get_post("usrPassword")) {
					$insUpd["usr_password"] = md5($this->input->get_post("usrPassword"));
				}
				$insUpd["usr_registered"] = Common::now();
				$usr_verify = md5($this->session->userdata("session_id").uniqid('', true));
				$insUpd["usr_verify"] = $usr_verify;
				$usrId = $this->user->insert($insUpd);

				if(isset($getCategory["USER"])) {
					$this->load->model("ent2cat");
					foreach($_POST as $key => $val) {
						if(preg_match("/cat_[0-9]*/msi", $key) and trim(strip_tags($val))) {
							$catId = mb_substr($key, 4);
							if(!isset($getEnt2cat[$catId])) {
								$insUpd = array(
									"e2c_entity" => "USER",
									"e2c_ent_id" => $usrId,
									"e2c_cat_id" =>	$catId,
									"e2c_int" => ((is_numeric($this->input->post("cat_".$catId)))?($this->input->post("cat_".$catId)):(NULl)),
									"e2c_text" => ((!is_numeric($this->input->post("cat_".$catId)))?($this->input->post("cat_".$catId)):(NULl)),
								);
								$this->ent2cat->insert($insUpd);
								if($catId == $this->config->item("categoryUSRFullname")) {
									$replace["<FULL_NAME>"] = $insUpd["e2c_text"];
								}
							}
						}
					}
				}

				// intézményi felhasználó
				$admin = FALSE;
				if($this->input->post("insName")) {
					$admin = TRUE;
					$this->load->model("institute");
					$getInstitute = $this->institute->getInstitute($where = "ins_name = '".$this->db->escape_str($this->input->post("insName"))."'");
					$this->load->model("usr2grp");
					$address = "";
					$fields = array(
						"insAddress_1",
						"insAddress_2",
						"insAddress_3",
						"insAddress_4",
						"insAddress",
					);
					foreach($fields as $field) {
						if($this->input->post($field)) {
							$address .= (($address)?(", "):("")) . $this->input->post($field);
						}
					}
					$cityId = NULL;
					if($this->input->post("insAddress_4")) {
						$this->load->model("city");
						$getCity = $this->city->getCity("city_name = '".$this->input->post("insAddress_4")."'");
						if(count($getCity)) {
							$cityId = $getCity[0]["cityId"];
						}
					}
					$this->usr2grp->insert(
						array(
							"u2g_usr_id" => $usrId,
							"u2g_grp_id" => 3,
							"u2g_ins_id" => ((count($getInstitute))?($getInstitute[0]["insId"]):(NULL)),
							"u2g_ins_name" => ((count($getInstitute))?(NULL):($this->input->post("insName"))),
							"u2g_city_id" => $cityId,
							"u2g_postal_code" => (($this->input->post("insAddress_3"))?($this->input->post("insAddress_3")):(NULL)),
							"u2g_ins_address" => (($address)?($address):(NULL)),
							"u2g_ins_address_raw" => (($this->input->post("insAddress"))?($this->input->post("insAddress")):(NULL)),
							"u2g_ins_website" => ((count($getInstitute))?(NULL):($this->input->post("insWebsite")))
						)
					);
				}
				

				$replace["<USR_EMAIL>"] = $this->input->post("usrEmail");
				$replace["<FULL_NAME>"] = ((isset($replace["<FULL_NAME>"]) and $replace["<FULL_NAME>"])?($replace["<FULL_NAME>"]):($replace["<USR_EMAIL>"]));
				$replace["<USR_PASSWORD>"] = $this->input->post("usrPassword");
				$replace["<USR_VERIFY>"] = base_url()."registration_activate/".$usr_verify."/";
				if($admin) {
					$replace["<ADDRESS_OF_INSTITUTE>"] = $address;
					$replace["<INS_NAME>"] = $this->input->post("insName");
					$replace["<URL_OF_INSTITUTE>"] = $this->input->post("insWebsite");
				}

				// pdf
				if($this->input->post("insName")) {
					$this->_gen_pdf(str_replace(array_keys($replace), $replace, $this->lang->line("ADMIN_REGISTRATION_PDF")), "reg_".$usrId.".pdf");
					$path_to_the_file = realpath(APPPATH."../".PDFS."reg_".$usrId.".pdf");
				}
				// email
				Common::sendEmail($this->input->post("usrEmail"), $this->lang->line(($admin)?("ADMIN_REGISTRATION_SUBJECT"):("VISITOR_REGISTRATION_SUBJECT")), $this->lang->line(($admin)?("ADMIN_REGISTRATION_EMAIL"):("VISITOR_REGISTRATION_EMAIL")), $replace, (($this->input->post("insName"))?($path_to_the_file):(NULL)));

				$response["success"] = TRUE;
				$response["usrEmail"] = $this->input->post("usrEmail");
			}
		}

		echo	json_encode($response);
	}


	function registration_success() {
		header("Content-Type: text/javascript");
		$params = array(
			"usrEmail" => $this->input->post("usrEmail"),
		);
		$success = $this->load->view("registration/success", $params, TRUE);
		echo	"\$('#modal').html('".$this->db->escape_str($success)."');";
		echo	"\$('#modal').addClass('alert_success');";
	}

	function registration_activate() {
		$this->db->cache_off();
		if(!$this->input->is_ajax_request()) {
			$jscallback = "
							$.ajax({
								type: 'POST',
								url: '".site_url()."registration_activate/".$this->uri->segment(2)."',
								beforeSend: function(xhr) {
									\$('#modal').mask('".$this->db->escape_str($this->lang->line("PLEASE_WAIT,_PROCESSING_IN_PROGRESS"))."');
								},
								success: function(data) {
									
								},
								async: true
							})
							.always(function() {\$('#body').unmask();});
							";
			$this->index(FALSE, FALSE, array("jscallback" => $jscallback));
		} else {
			header("Content-Type: text/javascript");
			$params = array();
			if($this->uri->segment(2)) {
				$this->load->model("user");
				$params["getUser"] = $this->user->getUser("usr_verify = '".$this->db->escape_str($this->uri->segment(2))."'");

				if($params["getUser"]) {
					$usrId = key($params["getUser"]);
					$this->user->update($usrId, array("usr_verify" => NULL));
					Common::sendEmail($params["getUser"][$usrId]["usrEmail"], $this->lang->line("ACCOUNT_ACTIVATED_AS_VISITOR_EMAIL_SUBJECT"), $this->lang->line("ACCOUNT_ACTIVATED_AS_VISITOR_EMAIL_BODY"), $replace = array("<FULL_NAME>" => (($params["getUser"][$usrId]["fullName"])?($params["getUser"][$usrId]["fullName"]):($params["getUser"][$usrId]["usrEmail"]))), $attach = NULL);
				} else {
					unset($params["getUser"]);
				}
			}
			
			$activate = $this->load->view("registration/activate", $params, TRUE);
			echo	"\$('#modal').html('".$this->db->escape_str($activate)."');";
			echo	"\$('#modal').addClass('alert_".((isset($params["getUser"]) and $params["getUser"])?("success"):("error"))."');";
			echo	"\$('#modal').width(400);";
			echo	"\$('#modal').modal({});";
		}
	}

	function forgot_password() {
		$response = array();
		if($this->input->post("usrEmail")) {
			$this->load->model("user");
			$getUser = $this->user->getUser("usr_email = '".$this->input->post("usrEmail")."' and usr_verify is null");
			if($getUser) {
				$newPassword = substr(uniqid("", true),0,8);

				$this->user->update(key($getUser), array("usr_password" => md5($newPassword)));

				Common::sendEmail($this->input->post("usrEmail"), $this->lang->line("COMMON_FORGOT_PASSWORD_EMAIL_SUBJECT"), $this->lang->line("COMMON_FORGOT_PASSWORD_EMAIL_BODY"), $replace = array("<USR_EMAIL>" => $this->input->post("usrEmail"), "<USR_PASSWORD>" => $newPassword, "<PAGE_URL>" => base_url()));

				$params = array(
					"usrEmail" => $this->input->post("usrEmail"),
				);
				$response["success"] = $this->load->view("page/forgot_password_success", $params, TRUE);;
			}
		}
		if($this->input->is_ajax_request()) {
			echo	json_encode($response);
		}
	}

	function settings() {

		/*
		if($this->session->userdata("usrProvider")) {
			redirect();
			exit;
		}
		*/
		$this->db->cache_off();
		
		if(!$this->session->userdata("usrId")) redirect("");
		$this->load->model("user");
		$response = array("error_password" => "", "error_email" => "", "error_code" => "");

		$params = $this->_sidebar();

		if($this->input->post("submit_password")) {
			$getUser = $this->user->getUser("usr_id = '".$this->session->userdata("usrId")."' and usr_verify is null and usr_password = '".md5($this->input->post("usrPasswordOld"))."'");
			if($getUser) {

				if(!$this->input->get_post("usrPassword")) {
					$response["error_password"] .= $this->lang->line("PASSWORD_IS_REQUIRED")."<br/>";
				}

				if($this->input->get_post("usrPassword") and $this->input->get_post("usrPassword") <> $this->input->get_post("usrPasswordRe")) {
					$response["error_password"] .= $this->lang->line("THE_ENTERED_PASSWORDS_ARE_NOT_THE_SAME");
				}

				if(!$response["error_password"]) {
					$this->user->update(key($getUser), array("usr_password" => md5($this->input->get_post("usrPassword"))));
					$this->session->set_flashdata("success_password", $this->lang->line("PASSWORD_CHANGED"));
					$this->db->trans_complete();
					// post controller hook meghivasa redirect elott
					require APPPATH . 'hooks/Daemon_hooks.php'; $hook = new Daemon_hooks(); $hook->call_daemon();
					redirect("settings");
				}

			} else {
				$response["error_password"] .= $this->lang->line("THE_OLD_PASSWORD_DOES_NOT_MATCH_THE_CURRENT_PASSWORD");
			}
		}
		
		if($this->input->post("submit_email")) {
			if(isset($_POST["usrEmailNew"]) and $this->input->post("usrEmailNew")) {
				$this->load->model("user");
				$getUser = $this->user->getUser($where = "usr_email = '".$this->db->escape_str($this->input->post("usrEmailNew"))."'");
				if($getUser) {
					$response["error_email"] .= $this->lang->line("THE_E-MAIL_ADDRESS_IS_RESERVED_PLEASE_SELECT_AN_OTHER")."<br/>";
				}
			}

			if(isset($_POST["usrEmailNew"])) {
				if(!preg_match("/^[^0-9][A-z0-9_-]+([.][A-z0-9_-]+)*[@][A-z0-9_-]+([.][A-z0-9_-]+)*[.][A-z]{2,4}$/i", $this->input->post("usrEmailNew"))) {
					$response["error_email"] .= $this->lang->line("THE_FORMAT_OF_THE_E-MAIL_ADDRESS_IS_INCORRECT")."<br/>";
				}
			}
			
			if(!$response["error_email"]) {
				$usr_code = rand(100000,999999);
				$usr_code_new = rand(100000,999999);
				$this->user->update(
					$this->session->userdata("usrId"),
					array(
						"usr_email_new" => $this->input->post("usrEmailNew"),
						"usr_code" => $usr_code,
						"usr_code_new" => $usr_code_new,
					)
				);
				$this->session->set_flashdata("success_email", $this->lang->line("EMAIL_ADDRESS_CHANGED"));
				
				$replace = array("<USR_CODE>" => $usr_code);
				// email
				Common::sendEmail($this->session->userdata("usrEmail"), $this->lang->line("COMMMON_EMAIL_CHANGE_EMAIL_SUBJECT"), $this->lang->line("COMMON_EMAIL_CHANGE_EMAIL_BODY"), $replace);
				
				$replace = array("<USR_CODE>" => $usr_code_new);
				// email
				Common::sendEmail($this->input->post("usrEmailNew"), $this->lang->line("COMMMON_EMAIL_CHANGE_EMAIL_SUBJECT"), $this->lang->line("COMMON_EMAIL_CHANGE_EMAIL_BODY"), $replace);
				$this->db->trans_complete();
				// post controller hook meghivasa redirect elott
				require APPPATH . 'hooks/Daemon_hooks.php'; $hook = new Daemon_hooks(); $hook->call_daemon();
				redirect("settings");
			}
		}
		
		if($this->input->post("submit_code")) {
			$getUser = current($this->user->getUser("usr_id = '".$this->session->userdata("usrId")."'"));
			if($getUser["usrCode"] == $this->input->post("usrCode") and $getUser["usrCodeNew"] == $this->input->post("usrCodeNew") and $getUser["usrEmailNew"]) {
				$this->user->update(
					$this->session->userdata("usrId"),
					array(
						"usr_email" => $getUser["usrEmailNew"],
						"usr_email_new" => NULL,
						"usr_code" => NULL,
						"usr_code_new" => NULL,
					)
				);
				$this->session->set_flashdata("success_email", str_replace("<USR_EMAIL>", $getUser["usrEmailNew"], $this->lang->line("EMAIL_ADDRESS_SUCCESFULLY_CHANGED")));
				$this->db->trans_complete();
				// post controller hook meghivasa redirect elott
				require APPPATH . 'hooks/Daemon_hooks.php'; $hook = new Daemon_hooks(); $hook->call_daemon();
				redirect("settings");
			} else {
				$response["error_code"] .= $this->lang->line("CODES_DOESNT_MATCH");
			}
		}

		$params["breadcrumbs"] = array(
			site_url() => $this->lang->line("HOME"),
			$this->lang->line("SETTINGS")
		);
		$params["title"] = $this->lang->line("SETTINGS");
		$params["response"] = $response;
		
		$params["getUser"] = current($this->user->getUser("usr_id = '".$this->session->userdata("usrId")."'"));

		$params["content"] = $this->load->view("page/settings", $params, TRUE);

		$this->load->view("template/page", $params);
	}

	function search() {
		if(empty($_POST)) {
			$_POST = $this->session->userdata("POST");
		} else {
			$this->session->set_userdata("POST", $_POST);
		}
		if(!strlen($this->input->post("searchtext"))) redirect("");
		$start = $this->uri->segment(2,0);
		$params = $this->_sidebar();

		$params["title"] = $this->lang->line("SEARCH_RESULTS") . " \"".$this->input->post("searchtext")."\"";
		$params["breadcrumbs"] = array(
			site_url() => $this->lang->line("HOME"),
			$params["title"]
		);

		$this->session->set_flashdata("POST", $_POST);
		$this->load->library("pagination");
		$this->load->model("search");
		$params["getSearchList"] = $this->search->getSearchList($this->input->post("searchtext"), $start, $limit = $this->config->item("searchPageSize"));
		$params["start"] = $start;
		$params["content"] = $this->load->view("page/search_results", $params, TRUE);

		$this->load->view("template/page", $params);
	}

	function advanced_search() {
		$start = $this->uri->segment(2,0);
		//Common::pr($this->session->userdata('POST'));
		if($start === "new") {
			$_POST = array();
			$this->session->unset_userdata('POST');
		}
		$params = $this->_sidebar();
		
		$params["breadcrumbs"] = array(
			site_url() => $this->lang->line("HOME"),
			$this->lang->line("MOVE2STUDY_SEARCH_ENGINE")
		);

		$params["PROGTYPE"] = Common::szotar("PROGTYPE");
		
		$this->load->model("country");
		$params["getCountry"] = $this->country->getCountry($where = "cou_presenter ".(($this->uri->segment(1) == "preview")?(" in ('I', 'N') "):(" = 'I' "))." and maj_presenter ".(($this->uri->segment(1) == "preview")?(" in ('I', 'N') "):(" = 'I' "))."", NULL, NULL, $fields = NULL, $query = NULL, $order = array("conName", "couName"), $dir = "ASC");

		$this->load->model("subject");
		$params["getSubject"] = $this->subject->getSubject("maj_presenter ".(($this->uri->segment(1) == "preview")?(" in ('I', 'N') "):(" = 'I' "))." and maj_id is not null");
		
		$this->load->model("category");
		$getTrainingLevel = $this->category->getCategory($where = "cat_entity = 'MAJ' and cat_id = '".$this->db->escape_str($this->config->item("categoryMAJTrainingLevelId"))."'");
		if(count($getTrainingLevel)) {
			$params["getTrainingLevel"] = explode("|", $getTrainingLevel["MAJ"][0]["catList"]);
		}
		
		$getLanguage = $this->category->getCategory($where = "cat_entity = 'MAJ' and cat_id = '".$this->db->escape_str($this->config->item("categoryMAJLanguageId"))."'");
		if(count($getLanguage)) {
			$params["getLanguage"] = explode("|", $getLanguage["MAJ"][0]["catList"]);
		}
		
		if(!count($_POST)) {
			$_POST = $this->session->userdata("POST");
			unset($_POST["searchtext"]);
		}

		if(is_array($_POST) and count($_POST)) {
			$this->session->set_userdata("POST", $_POST);
			$this->load->library("pagination");
			
			$major_where = $scholarship_where = NULL;
			
			// program type
			if($this->input->post("program_type")) {
				$in = "";
				foreach($this->input->post("program_type") as $pt)  {
					$in .= (($in)?(","):(""))."'".$this->db->escape_str($pt)."'";
				}
				$major_where .= (($major_where)?(" and "):("")) . " maj_prog_type in (".$in.") ";
			}

			// country
			if($this->input->post("cou")) {
				$in = "";
				foreach($this->input->post("cou") as $cou)  {
					$in .= (($in)?(","):(""))."'".$this->db->escape_str($cou)."'";
				}
				$major_where .= (($major_where)?(" and "):("")) . " cou_id in (".$in.") ";
				$scholarship_where .= (($scholarship_where)?(" and "):("")) . " cou_id in (".$in.") ";
			}

			// subject
			if($this->input->post("sub")) {
				$in = "";
				foreach($this->input->post("sub") as $sub)  {
					$in .= (($in)?(","):(""))."'".$this->db->escape_str($sub)."'";
				}
				$major_where .= (($major_where)?(" and "):("")) . " maj_sub_id in (".$in.") ";
			}

			// grade level
			if($this->input->post("grade_level")) {
				$in = "";
				foreach($this->input->post("grade_level") as $gl)  {
					$in .= (($in)?(","):(""))."'".$this->db->escape_str($gl)."'";
				}
				$major_where .= (($major_where)?(" and "):("")) . " coalesce(e2c.e2c_int, e2c.e2c_text) in (".$in.") ";
			}

			// language
			if($this->input->post("language")) {
				$in = "";
				foreach($this->input->post("language") as $lan)  {
					$in .= (($in)?(","):(""))."'".$this->db->escape_str($lan)."'";
				}
				$major_where .= (($major_where)?(" and "):("")) . " coalesce(language.e2c_int, language.e2c_text) in (".$in.") ";
				$scholarship_where .= (($scholarship_where)?(" and "):("")) . " coalesce(e2c.e2c_int, e2c.e2c_text) in (".$in.") ";
			}

			if(!$this->input->post("progTypes") or $this->input->post("progTypes") == "pt_study_abroad") {
				$this->load->model("major");
				$major_where .= (($major_where)?(" and "):("")) . " maj_presenter = 'I' ";
				$params["getMajor"] = $this->major->getMajor($major_where, $start, $limit = $this->config->item("searchPageSize"));
				//Common::pr($params["getMajor"]);
				$params["getMajorCount"] = $this->major->getMajorCount($major_where);
			} 
			if(!$this->input->post("progTypes") or $this->input->post("progTypes") == "pt_scholarships") {
				$this->load->model("scholarship");
				$scholarship_where .= (($scholarship_where)?(" and "):("")) . " sch_presenter = 'I' ";
				$params["getScholarship"] = $this->scholarship->getScholarship($scholarship_where, $start, $limit = $this->config->item("searchPageSize"));
				$params["getScholarshipCount"] = $this->scholarship->getScholarshipCount($scholarship_where);
			} 
			if(!$this->input->post("progTypes") or $this->input->post("progTypes") == "pt_internships") {
				
			} 
			if(!$this->input->post("progTypes") or $this->input->post("progTypes") == "pt_work_study") {
				
			}
			
			$params["find_by"] = $this->load->view("page/study_abroad_advanced_search", $params, TRUE);
			$params["start"] = $start;
		}
		
		$params["title"] = $this->lang->line("MOVE2STUDY_SEARCH_ENGINE");
		$this->load->model("search");
		//$params["getSearchList"] = $this->search->getSearchList($this->input->post("searchtext"));
		if($this->input->is_ajax_request()) {
			$this->load->view("page/study_abroad_advanced_search", $params);
		} else {
			$params["content"] = $this->load->view("page/advanced_search", $params, TRUE);
			$this->load->view("template/page", $params);
		}
	}

	function getInstitutes() {
		//header("Content-Type: text/javascript");
		$this->load->model("institute");
		$getInstitute = $this->institute->getInstitute($where = "ins_name like '%".$this->db->escape_str($this->input->post("query"))."%'");
		$ins = array();
		$insId = array();
		if(count($getInstitute)) {
			foreach($getInstitute as $ii => $insData) {
				$ins[] = $insData["insName"];
				$insId[] = $insData["insId"];
			}
		}
		echo json_encode(array("query" => $this->input->post("query"), "suggestions" => $ins, "data" => $insId));
	}
	
	function getCities() {
		//header("Content-Type: text/javascript");
		$this->load->model("city");
		$getCity = $this->city->getCity($where = "city_name like '%".$this->db->escape_str($this->input->post("query"))."%'");
		$ins = array();
		$insId = array();
		if(count($getCity)) {
			foreach($getCity as $ii => $cityData) {
				$ins[] = $cityData["cityName"];
				$insId[] = $cityData["cityId"];
			}
		}
		echo json_encode(array("query" => $this->input->post("query"), "suggestions" => $ins, "data" => $ins));
	}

	function contact_us() {
		$params = $this->_sidebar();

		$params["breadcrumbs"] = array(
			site_url() => $this->lang->line("HOME"),
			$this->lang->line("HAVE_QUESTIONS_CONTACT_US")
		);
		$params["title"] = $this->lang->line("HAVE_QUESTIONS_CONTACT_US");

		$params["content"] = $this->load->view("page/have_a_question", $params, TRUE);

		$this->load->view("template/page", $params);
	}

	function _sidebar($params = array()) {
		$this->load->model("article_model");
		$params["getTags"] = $this->article_model->getTags();
		$params["sidebar"] = $this->load->view("page/sidebar", $params, TRUE);
		return $params;
	}

	private function _gen_pdf($html, $name, $paper="A4") {
		$this->load->library("mpdf/mpdf");
		$mpdf=new mPDF("utf-8",$paper);
		
		// unwrap remove
		$html = str_replace(array("{unwrap}", "{/unwrap}"), array("", ""), $html);
		
		$mpdf->WriteHTML($html);
		$mpdf->Output(PDFS.$name, "F");
	}

}